<template>
  <div>
    <el-row>
      <el-col :span="4" class="branch-col">
        <el-select v-model="filter.state" size="medium" placeholder="请选择" @change="fetchData">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-input
          v-model="filter.search"
          placeholder="搜索或者过滤结果"
          suffix-icon="el-icon-search"
          size="medium"
          @keyup.enter.native="fetchData"
        />
      </el-col>
      <el-col :span="16">
        <el-button-group style="float:right">
          <el-button size="medium" type="success" @click="addDialogFormVisible = true">新建</el-button>
          <el-button class="del-branch" size="medium" type="primary" @click="drawer = true">编辑</el-button>
          <el-button size="medium" type="danger" @click="deleteMergeRequest">删除</el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <el-divider/>
    <el-row>
      <el-table
        v-loading="listLoading"
        :data="listData"
        :show-header="false"
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="left">
          <template slot-scope="{row}">
            <el-link  @click="getMergeCommits(row)" :underline="false"><strong>{{ row.title }}</strong></el-link>
            <br>
            !{{ row.iid }} <strong>·</strong> {{ row.state }} <strong>·</strong>
            {{ row.created_at | filterDurationTime }}&nbsp;
            by <strong>{{ row.author.name }}</strong> &nbsp;
            <i class="el-icon-s-operation"/>
            <el-tooltip content="目标分支">
              <span class="target" @click="gotoCommitList(row.target_branch)">
                {{ row.target_branch }}
              </span>
            </el-tooltip>
            <template v-if="row.labels !== ''">
              <el-tag
                v-for="item in row.labels.split(',')"
                style="margin-right: 4px;color:#eef0f2"
                :color="item | filterColor"
              >{{ item }}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="right">
          <template slot-scope="{row}">
            <i v-if="row.merge_status === 'cannot_be_merged'" class="el-icon-circle-close" title="无法自动合并"/>
            <i v-else class="el-icon-circle-check" title=""/>
            <br>
            更新于 {{ row.updated_at | filterDurationTime }}
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog title="新建合并请求" :visible.sync="addDialogFormVisible" @open="getProjectInfo">
      <el-form :model="addForm" label-position="top" label-width="20">
        <el-col :span="12">
          <el-form-item label="来源分支">
            <el-select v-model="addForm.sourceBranch" style="width: 95%">
              <el-option
                v-for="item in mergeBranch"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标分支">
            <el-select v-model="addForm.targetBranch" style="width: 95%">
              <el-option
                v-for="item in mergeBranch"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="createMergeView">确 定</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :with-header="false"
      :visible.sync="drawer"
      :direction="direction"
      @open="getAssignAndLabels"
    >
      <el-row :gutter="10">
        <el-col :span="14" style="margin-top: 40px;margin-left:20px">
          <el-button size="medium" type="success" @click="editMergedRequest">全部更新</el-button>
        </el-col>
        <el-col :span="6" style="margin-top: 40px;">
          <el-button size="medium" @click="drawer = false">取消</el-button>
        </el-col>
      </el-row>
      <el-divider/>
      <el-form ref="editForm" :model="editForm" label-width="60px">
        <el-form-item label="状态">
          <el-select v-model="editForm.state_event" placeholder="选择状态" style="width: 90%">
            <el-option
              v-for="item in stateEventOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="指派">
          <el-select
            v-model="editForm.assigneeId"
            v-loading="assigneeLoading"
            placeholder="选择指派"
            multiple
            style="width: 90%"
          >
            <el-option
              v-for="item in projectMembers"
              :key="item.id"
              :label="filterAssign(item)"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标记">
          <el-select v-model="editForm.labels" v-loading="labelLoading" multiple placeholder="选择标记" style="width: 90%">
            <el-option
              v-for="item in labelList"
              :key="item.name"
              :value="item.name"
            >
              <div :style="item | styleFilter"/>
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { getData, postData } from '@/api/requestData'
import { handleTimeDuration } from '@/utils/index'

export default {
  filters: {
    filterDurationTime(time) {
      return handleTimeDuration(time)
    },
    filterColor(val) {
      const color = {
        bug: '#d9534f',
        confirmed: '#d9534f',
        critical: '#d9534f',
        discussion: '#428bca',
        documentation: '#f0ad4e',
        enhancement: '#5cb85c',
        suggestion: '#428bca',
        support: '#f0ad4e'
      }
      return color[val]
    },
    styleFilter(v) {
      return 'display:inline-block;margin-right:3px;width: 10px;height: 10px;background-color:' + v.color
    }
  },
  data() {
    return {
      pid: this.$route.params.pid,
      pname: this.$route.params.pname,
      editForm: {
        state_event: '',
        assigneeId: [],
        labels: [],
        mergeIds: []
      },
      drawer: false,
      direction: 'rtl',
      listLoading: true,
      listData: [],
      options: [
        {label: '未关闭', value: 'opened'},
        {label: '已关闭', value: 'closed'},
        {label: '已合并', value: 'merged'},
        {label: '所有', value: 'all'}
      ],
      filter: {
        search: '',
        state: 'all',
      },
      mergeBranch: [],
      addDialogFormVisible: false,
      addForm: {
        sourceBranch: '',
        targetBranch: '',
        targetPid: ''
      },
      multipleSelection: [],
      stateEventOptions: [
        {label: '打开', value: 'reopen'},
        {label: '关闭', value: 'close'}
      ],
      projectMembers: [],
      assigneeLoading: true,
      labelList: [],
      labelLoading: true
    }
  },
  created() {
    this.addForm.targetPid = this.pid
    this.fetchData()
  },
  methods: {
    fetchData() {
      const params = this.filter
      getData('/git/public/merge/request/list/' + this.pid, params).then((response) => {
        this.listData = response.data
        this.listLoading = false
      }).catch(() => {})
    },
    editMergedRequest() {
      if (this.multipleSelection.length === 0) {
        return this.$message.info('请选择要编辑的合并')
      }
      this.editForm.labels = this.editForm.labels.join(',')
      this.editForm.assigneeId = this.editForm.assigneeId.join(',')
      for (var i = 0; i < this.multipleSelection.length; i++) {
        this.editForm.mergeIds.push(this.multipleSelection[i].iid)
      }
      this.editForm.mergeIds = this.editForm.mergeIds.join(',')
      postData('/git/edit/merge/request/' + this.pid, this.editForm).then((response) => {
        this.$message.success(response.message)
      }).catch(() => {})
    },
    getAssignAndLabels() {
      getData('/git/project/member/' + this.pid).then((response) => {
        this.projectMembers = response.data.memberList
        this.assigneeLoading = false
        getData('/git/public/project/labels/' + this.pid).then((res) => {
          this.labelList = res.data
          this.labelLoading = false
        }).catch(() => {})
      }).catch(() => {})
    },
    filterAssign(row) {
      return row.username + '/' + row.name
    },
    gotoCommitList(branch) {
      this.$router.push({'path': '/git/commit/list/' + this.pname + '/' + this.pid + '?branch=' + branch})
    },
    getProjectInfo() {
      const url = '/git/public/all/branches/' + this.pid
      getData(url).then((response) => {
        this.mergeBranch = response.data
      }).catch(() => {})
    },
    createMergeView() {
      if (this.addForm.sourceBranch === '' || this.addForm.targetBranch === '') {
        return this.$message.error('来源分支和目标分支必选')
      }
      if (this.addForm.sourceBranch === this.addForm.targetBranch) {
        return this.$message.error('必须选择不同的分支')
      }
      this.addDialogFormVisible = false
      const params = '?sourceBranch=' + this.addForm.sourceBranch + '&targetBranch=' + this.addForm.targetBranch + '&targetPid=' + this.addForm.targetPid
      this.$router.push({path: '/git/merged/create/' + this.pname + '/' + this.pid + params})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteMergeRequest() {
      if (this.multipleSelection.length === 0) {
        return this.$message.info('请选择要删除的合并')
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonType: 'warning',
        cancelButtonType: 'text',
        type: 'warning'
      }).then(() => {
        // 确认处理逻辑
        var iidStr = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          iidStr.push(this.multipleSelection[i].iid)
        }
        getData('/git/delete/merge/request/' + this.pid, {iid: iidStr.join(',')}).then((response) => {
          this.$message.success(response.message)
        }).catch(() => {})
      }).catch(() => {})
    },
    getMergeCommits(row) {
      this.$router.push({'path': '/git/merged/commit/' + this.pname + '/' + this.pid + '/' + row.iid})
    }
  }
}
</script>

<style scoped>
.target:hover {
  cursor: pointer
}
</style>
